package com.machine.bootstatemachine.machine;


import com.machine.bootstatemachine.dao.OrderMapper;
import com.machine.bootstatemachine.domain.Order;
import com.machine.bootstatemachine.enums.OrderEventEnum;
import com.machine.bootstatemachine.enums.OrderStatueEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.stereotype.Component;

/**
 * @Author dai
 * @Date 2021/12/27
 */
@Slf4j
@Component
public class OrderStateMachinePersist implements StateMachinePersist<OrderStatueEnum, OrderEventEnum, Order> {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 持久化状态
     * @param context
     * @param order
     * @throws Exception
     */
    @Override
    public void write(StateMachineContext<OrderStatueEnum, OrderEventEnum> context, Order order) throws Exception {
        log.info("持久化数据状态 orderId: {}, status: {}", order.getOrderId(), context.getState().getStatus());
        order.setStatus(context.getState().getStatus());
        orderMapper.updateById(order);
    }

    /**
     * 读取状态恢复状态机
     * @param order
     * @return
     * @throws Exception
     */
    @Override
    public StateMachineContext<OrderStatueEnum, OrderEventEnum> read(Order order) throws Exception {
        OrderStatueEnum statueEnum = OrderStatueEnum.UN_PAY;
        Order orderRecord = orderMapper.selectById(order.getId());
        if (orderRecord == null) {
            log.warn("未查到数据");
        } else {
            statueEnum = OrderStatueEnum.of(orderRecord.getStatus());
        }
        StateMachineContext<OrderStatueEnum, OrderEventEnum> machineContext =
                new DefaultStateMachineContext<>(statueEnum, null, null, null);
        log.info("读取状态 status: {}", statueEnum);
        return machineContext;
    }
}
